package com.example.demolearn_2.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class LazyLoadFragment extends BaseFragment{

    protected boolean isViewInitiated;//判断视图是否初始化
    protected boolean isVisibleToUser;//用户是否可见
    protected boolean isDataInitiated;//数据是否初始化

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected View initView() {
        return null;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
    }

    @Override
    protected void initData() {
        super.initData();
    }

    //在所有生命周期函数之前调用，查看是否可见
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    //准备加载数据，这里不是强制刷新
    public boolean prepareFetchData() {
        return prepareFetchData(false);
    }

    //用户强制刷新的话，就应该是用户主动进行刷新了，当然也要去取数据了，用户第一嘛
    public boolean prepareFetchData(boolean forceUpdate) {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            initData();
            isDataInitiated = true;
            return true;
        }
        return false;
    }
}
